import os

from flask import Blueprint, render_template, request, jsonify, redirect, url_for, g, session
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename

from apps.article import articleDao
from apps.user import userDao
from apps.user.userDao import *

user_bp = Blueprint('user', __name__, url_prefix='/user')

# 允许自由进入的路由
allow_route = ['/user/', '/user/userLogin', '/user/userLogout']
# 允许上传的文件类型
allowed_extensions = ['jpg', 'gif', 'png', 'bmp']


# 钩子函数,获取session中userId
@user_bp.before_app_request
def before_app():
    if request.path not in allow_route and request.path[0:7] != '/static':
        uid = session.get('uid')
        if not uid:
            return redirect(url_for('user.index'))
        else:
            g.user = selectUserById(uid)
    else:
        pass


# 钩子函数,获取文章条数
@user_bp.before_app_request
def QuertArticleNum():
    g.articleNum = articleDao.countArticle()[0]


# 定义一个过滤器,用于转码二进制文本(首页)
@user_bp.app_template_filter('decodeLite')
def content_decode(content):
    content = content
    return content[0:150] + '...'


@user_bp.route('/')
def index():
    return render_template('index.html')


@user_bp.route('/userLogin', methods=['POST', 'GET'])
def userLogin():
    if request.method == 'POST':
        userName = request.form.get('userName')
        password = request.form.get('password')
        user = selectUserBYUserName(userName)
        if user:
            if check_password_hash(user[2], password):
                session['uid'] = selectUserBYUserName(userName)[0]
                articles = articleDao.QueryArticle(0, 5)
                # 此处不能重定向,因为user.mainPage直接调用的g.user,而此时还没有g.user
                return render_template('article/mainPage.html', user=user, articleNum=g.articleNum, articles=articles)
            else:
                return render_template('index.html')
        else:
            return render_template('index.html')
    else:
        return render_template('index.html')


@user_bp.route('/mainPage')
def mainPage():
    if session.get('uid'):
        page = request.args.get('page')
        if page:
            articles = articleDao.QueryArticle((int(page) - 1) * 5, int(page) * 5)
            return render_template('article/mainPage.html', user=g.user, articleNum=g.articleNum, articles=articles)
        else:
            articles = articleDao.QueryArticle(0, 5)
            return render_template('article/mainPage.html', user=g.user, articleNum=g.articleNum, articles=articles)
    else:
        return redirect(url_for('user.index'))


# 检查手机号是否存在
@user_bp.route('/phoneCheck')
def phoneCheck():
    phone_num = request.args.get('phone_num')
    user = selectUserByPhone(phone_num)
    if user:
        return jsonify(code=400, msg='手机号已注册')
    else:
        return jsonify(code=200, msg='手机号无误')


# 用户注册
@user_bp.route('/userRegister', methods=['POST', 'GET'])
def userRegister():
    if request.method == 'POST':
        userName = request.form.get('userName')
        password = request.form.get('password')
        rePassword = request.form.get('rePassword')
        phone = request.form.get('phone')
        sex = request.form.get('sex')
        email = request.form.get('email')
        if password != rePassword:
            return render_template('user/userRegister.html', msg='两次输入密码不一致', user=g.user)
        user = selectUserBYUserName(userName)
        if user:
            return render_template('user/userRegister.html', msg='该用户已注册', user=g.user)
        insertUsers(userName, generate_password_hash(password), sex, phone, email)
        return redirect(url_for('user.index'))
    else:
        return render_template('user/userRegister.html', user=g.user)


@user_bp.route('/userUpdate', methods=['POST', 'GET'])
def userUpdate():
    if request.method == 'POST':
        id = request.form.get('id')
        columu = request.form.get("columu")
        if columu == 'icon':
            value = request.files.get('icon')
            # 获取文件名
            iconName = value.filename
            if iconName.rsplit('.')[-1] in allowed_extensions:
                # 将文件名格式化,转换成安全的文件名,保证文件名符合python命名规则
                secure_icon_name = secure_filename(iconName)
                icon_path = os.path.join(Config.UPLOAD_PHOTO_DIR, secure_icon_name)
                # 保存到项目中
                value.save(icon_path)
                # 更新数据库
                userDao.userUpdate(columu, iconName, id)
                return redirect(url_for('user.userCenter'))
            else:
                return render_template('user/userCenter.html', user=g.user, msg='图片格式不允许')
        # 非更新图片
        else:
            if columu == 'password':
                value = request.form.get('value')
                # 更新数据库
                userDao.userUpdate(columu, generate_password_hash(value), id)
                return redirect(url_for('user.userCenter'))
            else:
                value = request.form.get('value')
                # 更新数据库
                userDao.userUpdate(columu, value, id)
                return redirect(url_for('user.userCenter'))
    # 非POST请求
    else:
        return render_template('user/userCenter.html', user=g.user)


# 用户注销
@user_bp.route('/userLogout')
def userLogout():
    session.clear()
    return redirect(url_for('user.index'))


# 用户中心
@user_bp.route('/userCenter')
def userCenter():
    return render_template('user/userCenter.html', user=g.user)


# 内容管理
@user_bp.route('/contentManagement')
def contentManagement():
    userId = session.get('uid')
    articles = articleDao.QueryArticleByUserId(userId)
    favs = articleDao.QueryFavByUserId(userId)
    return render_template('article/contentManagement.html', user=g.user, articles=articles, favs=favs)


# 删除文章
@user_bp.route('/deleteArticle')
def deleteArticle():
    articleId = request.args.get('articleId')
    articleDao.deleteArticleByArticleId(articleId)
    return redirect(url_for('user.contentManagement'))


# 删除收藏
@user_bp.route('/deleteFav')
def deleteFav():
    favId = request.args.get('favId')
    articleDao.deleteFavById(favId)
    return redirect(url_for('user.contentManagement'))
